/*
 *                        .::::.
 *                      .::::::::.
 *                     :::::::::::
 *                  ..:::::::::::'
 *               '::::::::::::'
 *                 .::::::::::
 *            '::::::::::::::..
 *                 ..::::::::::::.
 *               ``::::::::::::::::
 *                ::::``:::::::::'        .:::.
 *               ::::'   ':::::'       .::::::::.
 *             .::::'      ::::     .:::::::'::::.
 *            .:::'       :::::  .:::::::::' ':::::.
 *           .::'        :::::.:::::::::'      ':::::.
 *          .::'         ::::::::::::::'         ``::::.
 *      ...:::           ::::::::::::'              ``::.
 *     ````':.          ':::::::::'                  ::::..
 *                        '.:::::'                    ':'````..
 *
 * @Author: byx
 * @Date: 2022-11-28 22:21:06
 * @LastEditors: byx
 * @LastEditTime: 2022-12-04 01:18:14
 * @version: 1.0
 * @Descripttion: wwww.byx1024.top
 */
import React, { Component } from 'react'
import { Card, Breadcrumb, Form, Button, Space, Input, Radio, Upload, Modal, message } from 'antd'
import { Link } from 'react-router-dom'
import { PlusOutlined } from '@ant-design/icons'

import ReactQuill from 'react-quill'
import 'react-quill/dist/quill.snow.css'

import Channel from 'components/Channel'
import styles from './index.module.scss'

import { baseURL } from 'utils/request'
import { addAritcle, getArticleById, updateArticle } from 'api/article'
export default class ArticlePublish extends Component {
  state = {
    // 文档封面类型
    type: 1,
    // 存放上传的文件列表
    fileList: [],
    // 图片预览
    showPreview: false,
    previewUrl: '',
    // 编辑是否有id
    id: this.props.match.params.id,
  }
  // 自定义form表单校验，需要使用受控组件 ref
  formRef = React.createRef()

  render() {
    const { type, fileList, showPreview, previewUrl, id } = this.state
    return (
      <div className={styles.root}>
        <Card
          title={
            <Breadcrumb separator=">">
              <Breadcrumb.Item>
                <Link to="/home">首页</Link>
              </Breadcrumb.Item>
              <Breadcrumb.Item>{id ? '编辑文章' : '发布文章'}</Breadcrumb.Item>
            </Breadcrumb>
          }
        >
          <Form
            ref={this.formRef}
            labelCol={{ span: 4 }}
            validateTrigger={['onChange', 'onBlur']}
            initialValues={{ content: '', type: 1 }}
            onFinish={this.onFinish}
          >
            <Form.Item
              label="标题"
              name="title"
              rules={[{ required: true, message: '文章的标题不能为空' }]}
            >
              <Input
                placeholder="请输入文章标题"
                style={{
                  width: 400,
                }}
              />
            </Form.Item>
            <Form.Item
              label="频道"
              name="channel_id"
              rules={[{ required: true, message: '请选择频道' }]}
            >
              <Channel></Channel>
            </Form.Item>
            <Form.Item label="封面" name="type">
              <Radio.Group onChange={this.changeType}>
                <Radio value={1}>单图</Radio>
                <Radio value={3}>三图</Radio>
                <Radio value={0}>无图</Radio>
              </Radio.Group>
            </Form.Item>
            {type !== 0 && (
              <Form.Item wrapperCol={{ offset: 4 }}>
                <Upload
                  name="image"
                  listType="picture-card"
                  fileList={fileList}
                  action={`${baseURL}upload`}
                  onChange={this.uploadImages}
                  onPreview={this.handlePreview}
                  beforeUpload={this.beforeUpload}
                >
                  {fileList.length < type && <PlusOutlined />}
                </Upload>
              </Form.Item>
            )}

            <Form.Item
              label="内容"
              name="content"
              rules={[{ required: true, message: '文章的内容不能为空' }]}
            >
              <ReactQuill theme="snow" placeholder="请输入文章内容"></ReactQuill>
            </Form.Item>
            <Form.Item wrapperCol={{ offset: 4 }}>
              <Space>
                <Button type="primary" htmlType="submit" size="large">
                  {id ? '编辑文章' : '发布文章'}
                </Button>
                <Button size="large" onClick={this.addDraft}>
                  存入草稿
                </Button>
              </Space>
            </Form.Item>
          </Form>
        </Card>
        <Modal
          visible={showPreview}
          title="图片预览"
          footer={null}
          onCancel={() => {
            this.setState({
              showPreview: false,
              previewUrl: '',
            })
          }}
        >
          <img alt="example" style={{ width: '100%' }} src={previewUrl} />
        </Modal>
      </div>
    )
  }

  // 页面加载完毕
  async componentDidMount() {
    console.log('页面加载完毕', this.state.id)
    console.log(this.props)
    if (this.state.id) {
      // 需要发送请求，获取文章详细信息
      const res = await getArticleById(this.state.id)
      // 处理请求结果，用来回显
      const values = { ...res.data }
      // 给表单设置 values 值
      this.formRef.current.setFieldsValue(values)
      // state中数据单独处理
      const fileList = res.data.cover.images.map(item => {
        return { url: item }
      })
      this.setState({
        fileList,
        type: res.data.cover.type,
      })
    }
  }

  // 发表文章&草稿公共代码抽离
  async save(vaules, draft) {
    // 1.对图片数量进行校验
    const { fileList, type } = this.state
    if (fileList.length !== type) return message.warn('上传的图片数量不正确')
    // 2.整理接口所需数据
    // 图片有两种情况需要判断
    const images = fileList.map(item => {
      return item.url || item.response.data.url
    })
    // 做判断是新增还是修改
    if (this.state.id) {
      // 4.修改文章-发送接口
      await updateArticle({ ...vaules, cover: { type, images }, id: this.state.id }, draft)
      this.props.history.push('/home/list')
      message.success('修改文章成功')
    } else {
      // 3.新增文章-发送请求
      await addAritcle({ ...vaules, cover: { type, images } }, draft)
      this.props.history.push('/home/list')
      message.success('添加文章成功')
    }
  }
  // 发布文章
  onFinish = vaules => {
    try {
      this.save(vaules, false)
    } catch (error) {
      console.log(error)
      message.error(error.message, 1)
    }
  }
  // 添加草稿
  addDraft = async () => {
    try {
      const vaules = await this.formRef.current.validateFields()
      this.save(vaules, true)
      message.success('保存草稿成功')
    } catch (error) {
      console.log(error)
      message.error(error.message, 1)
    }
  }
  // 封面的切换逻辑
  changeType = e => {
    this.setState({
      type: e.target.value,
      // 切换封面，图片应该做清空操作
      fileList: [],
    })
  }
  uploadImages = ({ fileList }) => {
    // 上传后，把回调的 fileList 修改到 state中
    this.setState({
      fileList,
    })
  }
  // 图片预览
  // 注意：如果fileList是将来回显的（也就是修改操作），通过url就能够访问到
  // 如果 fileList 文件是新增上传的，需要通过 file.response.data.url 来获取
  handlePreview = file => {
    console.log(file)
    // 定义各种情况的图片路径
    const previewUrl = file.url || file.response.data.url
    this.setState({
      showPreview: true,
      previewUrl,
    })
  }
  // 图片上传前的校验
  beforeUpload = file => {
    console.log(file)
    // 判断图片的大小 不能超过 500k
    if (file.size > 1024 * 500) {
      message.warn('上传的文件不能超过500kb')
      return Upload.LIST_IGNORE
    }
    if (!['image/jpeg', 'image/png'].includes(file.type)) {
      message.warn('只能上传png或者jpg图片')
      return Upload.LIST_IGNORE
    }
  }
}
